/* eslint-disable vue/no-unused-vars */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        show-index
        :expand-type="false"
        index-text="#"
        border
      >
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" style="color: lightGreen" v-if="scope.row.cat_deleted===false"></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditCateDialog(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCateById(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框区域 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form ref="addCateFormRef" :model="addCateForm" label-width="80px" :rules="addCateRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- props 配置对象  options 数据源 -->
          <el-cascader
            v-model="selectedkeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            size="mini"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框区域 -->
    <el-dialog title="编辑分类" :visible.sync="editCateDialogVisible" width="50%">
      <el-form ref="editCateFormRef" :model="editCateForm" label-width="100px">
        <el-form-item label="编辑分类" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateCommit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedkeys: [], // 选中的父级分类 ID
      parentCateList: [],
      addCateDialogVisible: false,
      deleteCateDialogVisible: false,
      editCateDialogVisible: false,
      addCateForm: { cat_name: "", cat_pid: 0, cat_level: 0 }, // cat_pid 为父级分类 Id
      editCateForm: {}, // 编辑分类数据存放表单
      queryInfo: { type: 3, pagenum: 1, pagesize: 5 }, // 查询条件
      cateList: [], // 商品分类的数据列表，默认为空
      total: 0, // 总数据条数
      // * TreeTable 指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "isOk"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ],
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      // * params 代表请求参数
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      // ! console.log(res.data); 测试返回数据结构
      // * 将数据列表赋值给 cateList
      this.cateList = res.data.result;
      this.total = res.data.total; // 为总数据条数赋值
    },

    // 监听 pagesize 改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getCateList();
    },

    // 监听 pagenum 改变
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage;
      this.getCateList();
    },

    // 显示添加分类对话框
    showAddCateDialog() {
      this.getParentCateList(); // 先获取父级分类对话框
      this.addCateDialogVisible = true;
    },

    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2, pagenum: 1, pagesize: 5 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类数据失败");
      }
      this.parentCateList = res.data.result;
    },

    // 级联选择器改变时
    parentCateChange() {
      // 判断 selectedKeys 的数组长度,对应级联选择器的层级
      if (this.selectedkeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedkeys[
          this.selectedkeys.length - 1
        ];
        this.addCateForm.cat_level = this.selectedkeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },

    // 添加分类对话框关闭时清空数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedkeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },

    // 提交添加分类
    // TODO: 知识点 async 与 await 必须是父子关系
    // TODO: v-model 不等于 :model(v-bind:model)
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.message.error("添加分类失败");
        }
        this.$message.success("添加分类成功");
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },

    // 获取要编辑的分类
    async showEditCateDialog(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status !== 200) {
        return this.message.error("获取分类数据失败");
      }
      this.editCateForm = res.data;
      this.editCateDialogVisible = true;
    },

    // 提交编辑的分类
    async editCateCommit(id) {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return;
        // 发起修改用户信息的网络请求
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          {
            cat_name: this.editCateForm.cat_name
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新分类信息失败");
        }
        // 提交修改成功后
        this.editCateDialogVisable = false;
        this.getCateList();
        this.$message.success("更新分类信息成功!");
      });
    },

    // 利用分类 Id 删除分类
    async deleteCateById(id) {
      // 弹框询问
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancleButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // 用户选择情况返回 2 种结果
      if (confirmResult !== "confirm") {
        this.$message.info("取消成功");
      } else {
        const { data: res } = await this.$http.delete("categories/" + id);
        if (res.meta.status !== 200) {
         
          return this.$message.error("删除角色失败");
        }
        this.getCateList();
        this.$message.success("删除角色成功");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 15px;
}
.el-cascader {
  width: 100%;
}
</style>